/*
 * $Id: djanet.js 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
 * Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
 * 
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/* $Revision: 7557b5d4d82b $ */
/* $Author: pgurumur $ */

dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.DateTextBox");
dojo.require("dijit.form.DropDownButton");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.form.Form");
dojo.require("dijit.form.SimpleTextarea");
dojo.require("dijit.form.Select");
dojo.require("dijit.form.Textarea");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.Menu");
dojo.require("dijit.TooltipDialog");
dojo.require("dojo.io.script");

dojo.require("dojox.data.QueryReadStore");
dojo.require("dojox.encoding.digests.MD5");
dojo.require("dojox.encoding.digests.SHA1");
dojo.require("dojox.grid.cells.dijit");
dojo.require("dojox.grid.DataGrid");
dojo.require("dojox.grid.EnhancedGrid");
dojo.require("dojox.grid.enhanced.plugins.NestedSorting");
dojo.require("dojox.validate.regexp");
dojo.require("dojo.parser");


var isLoggedIn = false;

function dict()
{
   this.length = 0;
   this.items = new Array();
   for (var ix = 0; ix < arguments.length; ix += 2) {
      if (typeof(arguments[ix + 1]) != 'undefined') {
         this.items[arguments[ix]] = arguments[ix + 1];
         this.length++;
      }
   }
   this.set = function(key, value)
   {
      var previous;
      if (typeof(value) != 'undefined') {
         if (typeof(this.items[key]) == 'undefined') {
            this.length++;
         }
         else {
            previous = this.items[key];
         }
         this.items[key] = value;
      }

      return previous;
   }
   this.get = function(key) 
   {
      return this.items[key];
   }
   this.has = function(key)
   {
      return typeof(this.items[key]) != 'undefined';
   }
   this.clear = function()
   {
      for (var ix in this.items) {
         delete this.items[ix];
      }

      this.length = 0;
   }
   this.remove = function(key)
   {
      var previous;
      if (typeof(this.items[key]) != 'undefined') {
         this.length--;
         var previous = this.items[key];
         delete this.items[key];
      }
      
      return previous;
   }
}

function djanetDialog(Title, Content)
{
   dialog = new dijit.Dialog({ title: Title, style: "width: 300px" });
   dialog.attr("content", Content);
   dialog.show();
}

function CheckLogin()
{
   var form = dojo.byId("id_djlogin");
   username = dojo.trim(form.djanet_username.value);
   password = dojo.trim(form.djanet_password.value);

   if (username.length && password.length) {
      dojo.xhrPost({
         url: form.action,
         handleAs: "text",
         content: {
            djanet_username: username,
            djanet_password: password,
         },
      });

      isLoggedIn = true;
   }
   else {
      djanetDialog("Error", "Username/Password cannot be null!");
   }
}

function GetRandomString()
{
   var randlength = dijit.byId('id_randstr_length').value;
   if ((randlength <= 21) && (randlength >= 6)) {
      dijit.byId('id_randstr_value').set('value', 
            GenerateRandomString(randlength));
   }
   else {
      djanetDialog("Error", "Invalid length: " + randlength);
   }
}

function GetDigest()
{
   var input = dojo.trim(dojo.byId("input_string").value);
   var select = dijit.byId("input_algorithms").get('value');
   var option = dojox.encoding.digests.outputTypes.Hex;

   if (input.length) {
      var digest = null;
      if (select == "SHA") {
         digest = dojox.encoding.digests.SHA1(input, option);
      }
      else if (select == "MD5") {
         digest = dojox.encoding.digests.MD5(input, option);
      }

      if (digest) {
         dojo.byId("dgst_string").value = dojo.trim(digest);
      }
   }
   else {
      djanetDialog("Error", "Input string cannot be a null value!");
   }
}

function GetWhoisInfo()
{
   var form = dojo.byId("whoisform");
   dojo.xhrPost({
      url: form.action,
      handleAs: "json",
      content: {
         asnumber: form.asnumber.value,
         ipaddress: form.ipaddress.value,
      },
      load: function(response, ioargs) {
         if (response.success == true) {
            node = dijit.byId("id_whoisinfo");
            node.set("value", response.whoisinfo);
         }
         else if (response.success == false) {
            djanetDialog("Error", "Cannot get whois info");
         }
      }
   });
}

function ClearWhoisForm()
{
   dijit.byId('id_asnumber').set('value', 0);
   dijit.byId('id_ipaddress').set('value', null);
   dijit.byId('id_whoisinfo').set('value', '');
}

function GetMaskInfo()
{
   var form = dojo.byId("maskform");
   dojo.xhrPost({
      url: form.action,
      handleAs: "json",
      content: {
         mask_value: form.mask_value.value,
         wildcard: form.wildcard.value,
      },
      load: function(response, ioargs) {
         if (response.success == true) {
            node = dijit.byId("id_netmask");
            node.set("value", response.netmask);
         }
         else if (response.success == false) {
            djanetDialog("Error", "Cannot get mask info");
         }
      }
   });
}

function ClearMaskForm()
{
   dijit.byId('id_mask_value').set('value', 24);
   dijit.byId('id_netmask').set('value', '');
}


function ClearStrForm()
{
   dijit.byId('id_randstr_length').set('value', 9);
   dijit.byId('id_randstr_value').set('value', null);
}

function GenerateRandomString(Length)
{
   var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz+";
   var randstring = '';

   for (var ix = 0; ix < Length; ix++) {
      var num = Math.floor(Math.random() * chars.length);
      randstring += chars.substring(num, (num + 1));
   }

   return randstring;

}

function ClearConsoleForm()
{
   dijit.byId("id_console_server").set("value", "");
   dijit.byId("id_description").set("value", '');
}

function AddConsoleServer()
{
   var form = dojo.byId("csformid");
   dojo.xhrPost({
      url: form.action,
      handleAs: "json",
      content: {
         description: form.description.value,
         console_server: form.console_server.value,
      },
      load: function(response, ioargs) {
         console.log(response);
         if (response.success == true) {
            djanetDialog("Message", response.message);
         }
         else if (response.success == false) {
            djanetDialog("Error", "Cannot add console server");
         }

         ClearConsoleForm();
      },
      error: function(error) {
         console.log("An unexpected error occured: " + error);
      }
   });
}

function xhttp()
{
   this.get = function(Url, NodeId)
   {
      var target = dojo.byId(NodeId);
      var args = {
         url: Url,
         callbackParamName: "callback",
         load: function(data) {
            target.innerHTML = "<pre>" + data + "</pre>";
         },
         error: function(error) {
            target.innerHTML = "An unexpected error occured: " + error;
         },
      };

      dojo.io.script.get(args);
   }
}

function http()
{
   this.errmesg = function(Message)
   {
      if (Message) {
         console.log("Error: " + Message);
         djanetDialog("Error", Message);
      }
   }
   this.get = function(Url, HandleAs, NodeId)
   {
      var target = dojo.byId(NodeId);
      var urlHandle = HandleAs;

      if (urlHandle == "text" || urlHandle == "json") {
         handleAs = urlHandle;
         var xhrArgs = {
            url: Url,
            handleAs: handleAs,
            preventCache: true,
            sync: true,
            handle: function(error, ioargs) {
               var message = null;
               var httpcode = ioargs.xhr.status;
               if (httpcode > 399) {
                  if (httpcode == 404) {
                     message = "The requested page was not found";
                  }
                  else if (httpcode == 403) {
                     message = "The requested page access if forbidden";
                  }
                  else if (httpcode == 500) {
                     message = "The server reported an error";
                  }
                  else {
                     message = "Unknown error: " + httpcode;
                  }
               }

               if (message) {
                  errmesg(message);
               }
            },
            load: function(data) {
               if (handleAs == "text") {
                  data = data.replace(/\n/g, "<br/>");
                  data = data.replace(/\t/g, "&nbsp;&nbsp;&nbsp;");
                  target.innerHTML = data;
               }
               else if (handleAs == "json") {
                  if (data.success == true) {
                     target.innerHTML = data.userdata;
                  }
               }
            },
            error: function(error) {
               errmesg("An unexpected error occured: " + error);
            }
         }
   
         var deferred = dojo.xhrGet(xhrArgs);
      }
      else {
         errmesg("Unknown method!");
      }
   }
}

function ShowRandStrDialog()
{
   dijit.byId("randstr_dialog").show();
}

function ShowDigestDialog()
{
   dijit.byId("digest_dialog").show();
}

function ShowNetmaskDialog()
{
   dijit.byId("netmask_dialog").show();
}

function ShowConsoleServer()
{
   dijit.byId("csform_dialog").show();
}


function clock()
{
   var node = 'djclock';
   var curdate = new Date();
   var currenthrs = curdate.getHours();
   var currentmins = curdate.getMinutes();
   var currentsecs = curdate.getSeconds();

   currentmins = (currentmins < 10 ? "0" : "") + currentmins;
   currentsecs = (currentsecs < 10 ? "0" : "") + currentsecs;

   var tod = (currenthrs < 12) ? "AM" : "PM";
   currenthrs = (currenthrs > 12) ? currenthrs - 12 : currenthrs;
   currenthrs = (currenthrs == 0) ? 12 : currenthrs;
   var year = curdate.getFullYear();
   var day = curdate.getDay();
   var month = curdate.getMonth();
   var mday = curdate.getDate();
   if (mday < 10) {
      mday = "0" + mday;
   }

   var arrday = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
   var arrmon = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
      "Aug","Sep","Oct","Nov","Dec");

   var curtime = arrday[day] + ", " + arrmon[month] + " " + mday + ", " + year +
         " " + currenthrs + ":" + currentmins + ":" + currentsecs + " " + tod;
   document.getElementById(node).innerHTML = curtime;
   setTimeout("clock()", 1000);
}
